package icasue.tools.compile.compilers.cloader;

import icasue.tools.compile.compilers.jfobjs.AbstractJavaFileObjects;
import icasue.tools.compile.compilers.jfobjs.JavaFileObjectGen;

import javax.tools.JavaFileObject;

/**
 * @Author: Qiao Hang
 * @CreateDate: 2020/12/7 下午2:29
 * @UpdateDate:
 * @Description:
 */
public class ClassLoaderCG extends ClassLoader {


    /**
     * This method is core, all class which be loading, will access find class method,
     * then invoke this method actually! Here will consider System classLoader first or classPath ClassLoader.
     * others will ref application's classLoader to load class metadata.
     * @param name
     * @return
     * @throws ClassNotFoundException
     */
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        try{
            JavaFileObject javaFileObject = AbstractJavaFileObjects.objectsGeneric.get(name);
            if(javaFileObject != null){
                byte[] bytes = ((JavaFileObjectGen)javaFileObject).getCompiledBytes();
                return defineClass(name, bytes, 0, bytes.length);
            }
            return ClassLoader.getSystemClassLoader().loadClass(name);
        } catch (Exception e){
            return Class.forName(name);
        }
    }
}
